<template>
  <div class="statisticsInfo-score">
    <div class="statisticsInfo-head">
      <div class="pieChartBox">
        <div class="pieChart">
          <echartsPie
            :echartsName="'scorePie-2'"
            :scoreOption="scoreOption"
            :title="'及格率统计'"
            :width="'264px'"
            :height="'206px'"
            @handleClickPie="handleClickPie"
            v-loading="tableLoading"
          />
          <div class="scoreList" style="flex: 1; overflow: hidden">
            <el-table
              ref="filterTable"
              :data="stuData"
              height="206"
              v-loading="tableLoading"
            >
              <el-table-column
                prop="realName"
                label="姓名"
                align="center"
                width="63"
              >
                <template slot-scope="scope" class="name">
                  <span :title="formatterName(scope.row)">
                    {{ formatterName(scope.row) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="score"
                label="成绩"
                align="center"
                sortable
                :formatter="formatterScore"
                width="70"
              />
            </el-table>
          </div>
        </div>
        <div class="searchInput">
          <el-input
            placeholder="学号/姓名"
            suffix-icon="el-input__icon el-icon-search"
            v-model="search"
          >
          </el-input>
        </div>
      </div>
      <div class="barChart">
        <carouselEchartsLine
          :taskCount="taskCount"
          :finshCount="finshCount"
          :studyCount="studyCount"
          :scoreCount="scoreCount"
          :width="`750px`"
          :height="`216px`"
          v-loading="tableLoading"
        />
      </div>
    </div>
    <div class="tableBox">
      <el-table
        ref="filterTable"
        :data="filterStuData"
        style="width: 100%"
        max-height="554"
        v-loading="tableLoading"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="stuNum" label="学号" align="center" sortable />
        <el-table-column
          prop="realName"
          label="姓名"
          align="center"
          :formatter="formatterName"
        />
        <el-table-column
          prop="className"
          label="班级"
          align="center"
          sortable
          column-key="className"
          :filters="filterClass"
          :filter-method="filterHandler_class"
        />
        <el-table-column
          prop="isPass"
          label="成绩"
          align="center"
          sortable
          :filters="filterScore"
          :filter-method="filterHandler"
          :formatter="formatterScore"
        />
        <el-table-column
          prop="taskCommitJson"
          label="教师评分"
          align="center"
          sortable
          :formatter="formatter"
        />
        <el-table-column label="详情" align="center" :formatter="formatter">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleStuInfo(scope.row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
        <!-- column-key="taskStateCount"
          :filters="[
            { value: '及格', text: '及格' },
            { value: '不及格', text: '不及格' },
          ]"
          :filter-method="filterHandler"
          :formatter="taskStateFormatter" -->
      </el-table>
    </div>
    <lineDialog
      :show="show"
      :currStu="currStu"
      :lineChartData="lineChartData"
      @handleClose="handleCloseDialog"
      :finshCount="finshCount"
      :studyCount="studyCount"
    />
  </div>
</template>

<script>
import { mapState } from "vuex";

const carouselEchartsLine = () =>
  import("@/components/carouselEcharts/carouselEchartsLine");
const echartsPie = () => import("@/components/echarts/echartsPie");
const lineDialog = () => import("./component/lineDialog.vue");
export default {
  components: {
    carouselEchartsLine,
    echartsPie,
    lineDialog,
  },
  data() {
    return {
      filterScore: [
        {
          text: "及格",
          value: true,
        },
        {
          text: "不及格",
          value: false,
        },
      ],
      show: false,
      lineChartData: {
        taskCount: [],
        scoreCount: {
          maxScore: [], // 最高分
          avgScore: [], // 平均分
          minScore: [], // 最低分
        },
      },
      currStu: {},
      stuData: [],
      search: "",
    };
  },
  props: {
    courseInfo: Object,
    taskCount: Array,
    finshCount: Object,
    studyCount: Object,
    scoreOption: Object,
    reviewOption: Object,
    studenData: {
      type: Array,
      default: function () {
        return [];
      },
    },
    studentsList: Array, // 选了这门课的学生
    scoreCount: Object,
    tableLoading: Boolean,
    taskIDforTaskGruopID: Object,
  },
  computed: {
    ...mapState({
      classList: (state) => state.class.classList
    }),
    filterClass() {
      let classList = [];
      this.studenData.forEach((item) => {
        if (
          item.className &&
          !classList.some((citem) => citem.value == item.className)
        ) {
          classList.push({ text: item.className, value: item.className, classID: item.classID });
        }
      });
      // 把课程原有班级也加上
      if (this.filterCourseClass?.length) {
        this.filterCourseClass.forEach(item => {
          if (item.className && !classList.some((citem) => citem.value == item.className)) {
            classList.push({ text: item.className, value: item.className, classID: item.classID });
          }
        })
      }
      return classList;
    },
    // 获取当前课程班级数据
    filterCourseClass() {
      if (this.courseInfo.classIDList) {
        const classList = this.courseInfo.classIDList.split(',').map(i => Number(i))
        return this.classList.filter(i => classList.some(s => i.classID == s))
      } else return []
    },
    filterStuData() {
      if (this.search) {
        return this.studenData.filter(
          (item) =>
            item.realName?.indexOf(this.search) !== -1 ||
            item.stuNum?.indexOf(this.search) !== -1
        );
      }
      return this.studenData;
    },
  },
  updated() {
    this.stuData = this.studenData;
  },
  methods: {
    filterHandler(value, row, column) {
      const property = column["property"];
      return row[property] === value;
    },
    // 过滤班级信息
    filterHandler_class(value, row, column) {
      const property = column["property"];
      const cData = column.filters.find(item => item.value == value)
      let uOtherClassList = [] 
      if (row.otherClassIDList) {
        uOtherClassList = row.otherClassIDList.split(',').map(i => Number(i))
      }
      return row[property] === value || uOtherClassList.indexOf(cData.classID) !== -1;
    },
    taskStateFormatter(row, column) {
      const userID = row.userID;
      const findStuData = this.studentsList.find(
        (item) => item.userID === userID
      );
      if (findStuData) {
        if (
          findStuData.studyingTaskIDArray.length ||
          findStuData.notStartTaskIDArray.length
        ) {
          this.$set(row, "taskStateCount", "有未完成任务");
          return "有未完成任务";
        } else {
          this.$set(row, "taskStateCount", "全部完成");
          return "全部完成";
        }
      } else {
        this.$set(row, "taskStateCount", "有未完成任务");
        return "有未完成任务";
      }
    },
    reviewStateFormatter(row, column) {
      let context = "";
      row.allTaskResultsInChooseNo.forEach((taskItem, t) => {
        let noReview = taskItem.guidelines.filter(
          (guideline) =>
            guideline.guidelineComment == "" &&
            (guideline.guidelineScore == -8 ||
              guideline.gameOrExciseScore == -8)
        );
        if (noReview.length == taskItem.guidelines.length) {
          context = "有未批阅任务";
          return;
        }
        let reviewing = taskItem.guidelines.filter(
          (guideline) =>
            guideline.guidelineComment !== "" &&
            (guideline.guidelineScore !== -8 ||
              guideline.gameOrExciseScore !== -8)
        );
        if (
          reviewing.length !== 0 &&
          reviewing.length == taskItem.guidelines.length &&
          context !== "有未批阅任务"
        ) {
          context = "已全部批阅";
        } else {
          if (!taskItem.guidelines.length) return;
          context = "有未批阅任务";
        }
      });
      this.$set(row, "reviewStateCount", context);
      return context;
    },
    formatter() {
      return "无";
    },
    // 格式化默认分数
    formatterScore(row) {
      if (Number(row.score) < 60) {
        this.$set(row, "isPass", false);
      } else {
        this.$set(row, "isPass", true);
      }
      return Number(row.score);
    },
    handleCloseDialog() {
      this.show = false;
      this.lineChartData = {
        taskCount: [],
        scoreCount: {
          maxScore: [], // 最高分
          avgScore: [], // 平均分
          minScore: [], // 最低分
        },
      };
    },
    handleStuInfo(row, None, that) {
      that = that || this
      // 判断是否存在学习数据 没有则调用父组件的函数获取该学生的学习数据
      if (!row.allTaskResultsInChooseNo || row.isGetOnlyTask) {
        const findUserData = that.studentsList.find(item => item.userID == row.userID)
        if (findUserData?.allTaskResultsInChooseNo && findUserData?.getAllTask && !findUserData.isGetOnlyTask) row.allTaskResultsInChooseNo = findUserData.allTaskResultsInChooseNo
        else return that.handleGetStuData(row.userID, that.handleStuInfo, {row, None, that})
      }
      that.currStu = row;
      that.handleFilterScore();
      that.show = true;
    },
    handleFilterScore() {
      let data = this.handleFormatTask(this.currStu);
      // 将任务组统计
      this.courseInfo.content.forEach((item) => {
        item.tasks.forEach((titem) => {
          this.lineChartData.taskCount.push({
            value: titem.name,
            taskGroupID: item.taskGroupID,
            taskID: titem.taskID,
          });
        });
      });

      // 给任务初始化数据
      this.lineChartData.taskCount.forEach((item, index) => {
        // 遍历对象 将每一个key都遍历一遍 item.key为数组 将key的值设为
        Object.keys(this.lineChartData.scoreCount).forEach((item) => {
          this.lineChartData.scoreCount[item][index] = 0;
        });
      });

      let countScore = Object.assign({}, this.lineChartData.scoreCount);
      // 当课程没有数据时
      if (!data.length) return;

      // 查找所有的任务数据
      this.lineChartData.taskCount.forEach((item, index) => {
        let findGourp = data.filter((ritem) => {
          return ritem.taskID === item.taskID;
        });
        // 将所有的任务数据 以任务的索引值为基准赋值给对应属性
        if (findGourp.length) {
          findGourp.forEach((fitem) => {
            Object.keys(countScore).forEach((oitem) => {
              countScore[oitem][index] = fitem[oitem];
            });
          });
          this.lineChartData.scoreCount = countScore;
        }
      });
    },
    handleFormatTask(stuData) {
      let taskArrData = [];
      stuData.allTaskResultsInChooseNo.forEach((task, index) => {
        let max = 0;
        let min = 0;
        let avg = 0;
        let count = 0;
        task.guidelines.forEach((guideline) => {
          if (guideline.guidelineScore > 0) {
            count = count + Number(guideline.guidelineScore);
            if (guideline.guidelineScore > max) {
              max = guideline.guidelineScore;
              if (index === 0) min = guideline.guidelineScore;
              return;
            }
            if (guideline.guidelineScore < min) {
              min = guideline.guidelineScore;
            }
          }
        });
        if (max === 0) {
          if (task.taskScore) {
            if (Number(task.taskScore) > max) {
              max = Number(task.taskScore);
              // min = Number(task.taskScore);
              count = Number(task.taskScore);
            }
          }
        }
        avg = (count / task.guidelines.length).toFixed(2);
        taskArrData.push({
          avgScore: avg,
          currNo: this.courseInfo.currNo,
          maxScore: max,
          minScore: min,
          taskID: task.taskID,
        });
      });
      return taskArrData;
    },
    // 格式化姓名
    formatterName(row) {
      return (
        row.realName || row.nickName || row.email || row.regName || row.stuNum
      );
    },
    handleClickPie(item) {
      this.stuData = item.data.children;
    },
    handleGetStuData(userID, fn, data) {
      this.$emit("getStuData", userID, fn, data)
    }
  },
};
</script>

<style lang="stylus">
.statisticsInfo-score {
  .statisticsInfo-head {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .pieChartBox {
      height: 252px;
      display: flex;
      flex-flow: column;
      justify-content: space-between;
      align-items: flex-start;

      .pieChart {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-radius: 10px;
        background-color: #ffffff;
        width: 398px;
        height: 206px;
        overflow: hidden;

        .scoreList {
          border-left: solid 1px rgba(112, 112, 112, 0.23);

          th, td {
            padding: 0;
          }

          td {
            div {
              height: 25px;
            }
          }

          div {
            padding-left: 0;
            padding-right: 0;
          }

          div.cell {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }

      .searchInput {
        .el-input {
          width: 230px;

          .el-input__inner {
            height: 36px;
            background-color: #ffffff;
            border: solid 1px rgba(112, 112, 112, 0.2);
          }
        }
      }
    }

    .barChart {
      width: 750px;

      .carouselEcharts {
        margin: 0;
        box-shadow: none;
        background: #fff;
        border-radius: 10px;
      }

      .echartsBar {
        padding: 0;
      }
    }
  }

  .tableBox {
    margin-top: 10px;
  }
}
</style>